//
//  StoryBrowserView.m
//  iPing
//
//  Created by Thomas on 8/16/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "StoryBrowserView.h"
#import "TCSGStory.h"


@implementation StoryBrowserView
- (id)init
{
	self = [super init];
	MainView = [[WebView alloc] init];
	return self;
}
-(void)awakeFromNib
{
	chapter = 0;
	[MainView setMainFrameURL:[TCSGGeneralMethods fullStoryPathForHTMLCode:[self getHTMLCode]]];
}
-(void)setStoryHTMLCode:(NSString *)code;
{
	storyHTMLCode = nil;
	[storyHTMLCode release];
	storyHTMLCode = code;
	[storyHTMLCode retain];
}
-(NSString *)getHTMLCode
{
	return storyHTMLCode;
}

-(IBAction)setChapterInWebView:(id)pID
{
	if([pID indexOfSelectedItem]==0)
	{
		[MainView setMainFrameURL:[TCSGGeneralMethods fullStoryPathForHTMLCode:[self getHTMLCode]]];
	} else
	{
		[self setChapter:[pID indexOfSelectedItem]];

	}
 
}
-(IBAction)changeChapter:(id)pID
{
	NSLog(@"chapter: %i, tag: %i",chapter,[pID tag],nil);
	if([pID tag]==1 && chapter!=0)
	{
		NSArray *storyArray = [NSArray arrayWithContentsOfFile:[TCSGGeneralMethods plistPathForHTMLCode:[self getHTMLCode]]];
		if(chapter<([storyArray count]))
		{
			[self setChapter:(chapter+1)];
		}
	}else if ([pID tag]==0 && chapter>1)
	{
		[self setChapter:(chapter-1)];
	} else if (chapter == 0 && [pID tag]==1)
	{
		[self setChapter:1];
	} else if (chapter == 1 && [pID tag]==0)
	{
		[MainView setMainFrameURL:[TCSGGeneralMethods fullStoryPathForHTMLCode:[self getHTMLCode]]];
	}
}
-(void)setChapter:(int)chapterNumber
{
	 
	NSArray *storyArray = [NSArray arrayWithContentsOfFile:[TCSGGeneralMethods plistPathForHTMLCode:[self getHTMLCode]]];
	NSString *chapterString = [storyArray objectAtIndex:(chapterNumber-1)];
	[chapterString writeToFile:[[TCSGGeneralMethods tempFolder] stringByAppendingPathComponent:[@"tmpHTML" stringByAppendingPathExtension:@"html"]] 
									   atomically:YES 
										 encoding:NSUTF8StringEncoding 
											error:nil];
	[MainView setMainFrameURL:[[TCSGGeneralMethods tempFolder] stringByAppendingPathComponent:[@"tmpHTML" stringByAppendingPathExtension:@"html"]]];
	chapter = chapterNumber;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"BrowserChapter" object:[NSNumber numberWithInt:chapter]];
	TCSGStory *story = [TCSGStory setLastReadChapters:chapterNumber forHTMLCode:[self getHTMLCode] inManagedObjectContext:managedObjectContext];
	
}

@end
